package fr.ensisa.sunspot.actor.client;

import fr.ensisa.sunspot.actor.AbstractActor;
import fr.ensisa.sunspot.actor.IActor;
import fr.ensisa.sunspot.actor.Template;
import fr.ensisa.sunspot.actor.client.keyboard.Keyboard_simulator;
import fr.ensisa.sunspot.event.AbstractEvent;
import fr.ensisa.sunspot.event.DwFlagsEvent;
import fr.ensisa.sunspot.event.IEvent;
import fr.ensisa.sunspot.event.MessageEvent;
import fr.ensisa.sunspot.event.StringEvent;
import fr.ensisa.sunspot.event.TemplateEvent;

public class KeyboardActor extends AbstractActor {
	
	private Keyboard_simulator keyboard_simulator;

	public KeyboardActor() {
		super(IActor.KIND_WRITER);
		setTemplate(this.BuildTemplate());
	}
	
	private Template BuildTemplate() {
		Template template = new Template();
		TemplateEvent event = new TemplateEvent(IEvent.MAJOR_KEYBOARD, IEvent.MINOR_NO, IEvent.STATE_EMPTY);
		template.addEvent(event);
		return template;
	}

	@Override
	public int getID() {
		return 15;
	}

	private Keyboard_simulator getKeyboard_simulator() {
		if (keyboard_simulator==null) keyboard_simulator = new Keyboard_simulator();
		return keyboard_simulator;
	}

	@Override
	public int process(long timeStamp, IEvent event) {
		if (! (event instanceof AbstractEvent)) return IActor.RETURN_DONOTHING;
		switch (event.getMinor()) {
		case IEvent.MINOR_Keybd_event:
			this.Exec_Keybd_event((DwFlagsEvent) event);
			break;
		case IEvent.MINOR_SetForegroundWindow:
			this.Exec_SetForegroundWindow((StringEvent) event);
			break;
		case IEvent.MINOR_PostMessage:
			this.Exec_PostMessage((MessageEvent) event);
			break;
		case IEvent.MINOR_SendMessage:
			this.Exec_SendMessage((MessageEvent) event);
			break;
		}
		return IActor.RETURN_DONOTHING;
	}
	
	private void Exec_SendMessage(MessageEvent event) {
		getKeyboard_simulator().SendMessage(event.getWindow(), event.getUint(), event.getBvk(), event.getI());
	}

	private void Exec_PostMessage(MessageEvent event) {
		getKeyboard_simulator().PostMessage(event.getWindow(), event.getUint(), event.getBvk(), event.getI());
	}

	private void Exec_Keybd_event(DwFlagsEvent event) {
		getKeyboard_simulator().Keybd_event(event.getbVk(), event.getDwFlags());
	}
	
	private void Exec_SetForegroundWindow(StringEvent event) {
		getKeyboard_simulator().SetForegroundWindow(event.getString());
	}
	
}
